package daily.jun0617;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JComboBoxTest {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShow());
    }

    public static void createAndShow() {
        //1.创建窗体
        JFrame jFrame = new JFrame("单选框按钮");
        //2.为窗体设置大小，位置等属性
        jFrame.setBounds(300, 400, 400, 300);
        jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE);
        jFrame.setVisible(true);
        //3.设置窗体布局
        jFrame.setLayout(new BorderLayout());

        //4.创建下拉框组件并添加选项
        JComboBox<String> stringComboBox = new JComboBox<>();
        stringComboBox.addItem("请选择角色");
        stringComboBox.addItem("张三");
        stringComboBox.addItem("李四");
        stringComboBox.addItem("王五");
        stringComboBox.addItem("赵六");
        stringComboBox.addItem("田七");

        //5.创建文本输入框
        JTextField textField = new JTextField(20);
        //6.为下拉框注册监听器
        stringComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //获取当前所选项的名称
                String item = (String) stringComboBox.getSelectedItem();
                if ("请选择城市".equals(item)) {
                    textField.setText("");
                } else {
                    textField.setText("法外狂魔" + item);
                }
            }
        });
        //7.创建JPanel面板
        JPanel panel = new JPanel();
        panel.add(stringComboBox);
        panel.add(textField);
        //8.将JPanel面板添加到窗体
        jFrame.add(panel, BorderLayout.PAGE_START);
    }
}
